/**
 * submitform.js same as shiftform
 * submit form for ajax summit & format result
 * =======================================================
 * Author: mohanlan
 * Email: mohanlan2014@sina.com
 *
 * use case:
 * $('form').submitform.js({
 *   loadingMessage: '加载提示',    // 可选，默认为“正在提交表单...”
 *   successMessage: '提交成功信息',   // 可选，默认为“表单提交成功”，优先显示服务器返回的成功信息
 *   failureMessage: '提交失败信息',   // 可选，默认为“表单提交失败”，优先显示服务器返回的业务失败信息
 *   errorMessage:  '提交出错信息',   //  可选，默认为“表单提交出错”，表示提交非业务出错信息
 *   beforeSubmit:    function(el) { // 通常做表单校验 },    //  可选，Ajax提交前执行函数
 *   success: function(el, backdrop, message) { // 提交成功callback },    //  可选
 *            string   selector-triggerEvent                            //  可选
 *   successUrl: test //  成功跳转的url
 *   failure: function(el, backdrop, message) { // 提交失败callback }    //  可选
 *   failureUrl: test //  失败跳转的url
 * })
 * 
 */

(function(root, factory) {
  
  'use strict'
  
  if(typeof define === 'function' && define.amd) {
    define(['zepto'], factory)
  } else if(typeof module === 'object' && module.exports) {
    module.exports = function(root, Zepto) {
      if (Zepto === undefined) {
        if (typeof window !== 'undefined') {
          Zepto = require('zepto')
        } else {
          Zepto = require('zepto')(root)
        }
      }
      factory(Zepto)
      return Zepto
    }
  } else {
    factory(root.Zepto)
  }
}(this, function($) {
  'use strict';

  $.fn.submitform = function(option) {
    
    var options = $.extend({
      loadingMessage: '正在提交表单...',
      successMessage: '表单提交成功',
      failureMessage: '表单提交失败',
      errorMessage: '表单提交出错',
      beforeSubmit: null,
      success: null,
      successUrl: null,
      failure: null,
      failureUrl: null,
    },option)

    function checkForm(el) {
      if(el.tagName.toUpperCase() != 'FORM') return
      var $form = $(el)
      // set form position relative
      $form.css('position', 'relative')

      var startSubmit = function(e) {
        e.preventDefault()
        if(e.target != e.currentTarget) return
        if(!options.beforeSubmit || options.beforeSubmit.call(this, el)) {

          // serialize parameters
          var parameters = $form.serializeArray()

          // showPreloader first
          var $preloader = $.showPreloader(options.loadingMessage)

          // function for changing backdrop display mesage
          var changeBackdropMessage = function(message, clazz, callback, url) {
            
            // function for changing preloader display message
            $($preloader).addClass(clazz ? clazz : '')
            $($preloader).find('.modal-title').html(message)

            if(callback && typeof callback === 'object') {
              
              callback(el, $backdrop[0], message)
              setTimeout(function() {
                url == null ?  window.location.reload() : window.location.href = url;
              }, 1500)
            } else {
              setTimeout(function() {
                url == null ?  window.location.reload() : window.location.href = url;
              }, 1500)
            }
          }
          
          // ajax post data after 1s
          // ajax post data after 1s
          setTimeout(function() {
            $.ajax({
              type: $form.attr('method'),
              url:  $form.attr('action'),
              data: parameters
            }).done(function(data) {
              data = JSON.parse(data)
              if(parseInt(data.code) == 0) {  
                changeBackdropMessage(data.message || options.successMessage, 'submit-success', options.success, data.successUrl || options.successUrl)
              } else {
                changeBackdropMessage(data.message || options.failureMessage, 'submit-error', options.failure, data.failureUrl || options.failureUrl)
              }
            }).fail(function() {
              changeBackdropMessage(options.errorMessage, 'submit-error')
            })
          }, 1000)
          
        }
      }

      $form.on('click', '[type="submit"]', startSubmit)
      
      $form.on('click', '[data-shift-submit="true"]', startSubmit)
      
    }

    return this.each(function() {
      checkForm(this)
    })

  }

  $.fn.submitform.noConflict = function() {
    $.fn.submitform = old
    return this
  }
  
}));